package com.report.reportserver.controller;

import com.report.reportserver.model.YamlModel;
import com.report.reportserver.service.YamlService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yaml.snakeyaml.Yaml;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @ ClassName: YamlController
 * @ Description：返回Yaml组件的各种内容
 * @ Modified By：
 * @ Version:
 * @ Author     ：LiYing
 * @ Date       ：Created in 10:48 2022/3/1
 */
@Controller
@RequestMapping(value = "/yaml")
public class YamlController {
    @Autowired
    YamlService yamlService;

    @RequestMapping(value = "/yamlid")
    public @ResponseBody
    Object yamlid(HttpServletRequest request) {
        int id = Integer.parseInt(request.getParameter("id"));
        YamlModel y = yamlService.queryYamlById(id);
        String content = y.getContent();
        Yaml yaml = new Yaml();
        Map<String, Object> map = (Map<String, Object>) yaml.load(content);

        JSONObject jsonObject = new JSONObject(map);
        return jsonObject.toString();
    }

    @RequestMapping(value = "/yamlname")
    public @ResponseBody
    Object yamlname(HttpServletRequest request) {
        String name = request.getParameter("name");
        YamlModel y = yamlService.queryYamlByName(name);
        if (y == null){
            return "Null";
        }
        String content = y.getContent();
        Yaml yaml = new Yaml();
        Map<String, Object> map = (Map<String, Object>) yaml.load(content);

        JSONObject jsonObject = new JSONObject(map);
        return jsonObject.toString();
    }

    @RequestMapping(value = "/yamltype")
    public @ResponseBody
    Object yamltype(HttpServletRequest request) {
        int type = Integer.parseInt(request.getParameter("type"));
        //查询所有符合type的YamlModel对象
        List<String> list = yamlService.queryYamlByType(type);

        return list;
    }
}
